#!/bin/bash 
# 设置命令标题名称
echo -ne "\e]2;银河麒麟V10Sp1工具箱\a"

# 确保脚本在终端中运行
if [ -z "$TERM" ]; then
    # 如果没有终端，尝试启动一个终端来运行脚本
    x-terminal-emulator -e "$0"
    exit 0
fi

# 颜色定义
red='\033[0;31m' 
green='\033[0;32m' 
yellow='\033[0;33m'
blue='\033[0;34m' 
cyan='\033[0;36m'
magenta='\033[0;35m' 
reset='\033[0m'
nc='\033[0m'

# 优化图标路径检查
icon_path="/usr/share/icons/hicolor/48x48/apps/xq-kylin-tools.png"
[[ ! -f "$icon_path" ]] && icon_path=""  # 图标不存在时不显示

# ====================== 通知工具函数 ======================
# 桌面通知与终端提示函数
show_notification() { 
    local title="$1" message="$2" level="$3" icon="${4:-}"
    case "$level" in
        "success") color="$green"; urgency="normal" ;;
        "warning") color="$yellow"; urgency="normal" ;;
        "error")   color="$red"; urgency="critical" ;;
        *)         color="$nc"; urgency="normal" ;;
    esac
    echo -e "\n${color}【$title】${message}${NC}"
    # 发送桌面通知
    if command -v notify-send &> /dev/null; then
        if [[ -n "$icon" && -f "$icon" ]]; then
            notify-send -u "$urgency" -i "$icon" "$title" "$message" 2>/dev/null || true
        else
            notify-send -u "$urgency" "$title" "$message" 2>/dev/null || true
        fi
    fi
}

# ====================== 权限检查与获取函数 ======================
# 错误处理函数 - 防止闪退并提示用户
handle_error() {
    local message="$1"
    echo -e "\n${red}【错误】${message}${NC}"
    show_notification "操作失败" "${message}" "error" "$icon_path"
    read -p "按Enter键继续或关闭窗口..."  # 防止闪退，等待用户确认
}
echo -e "${blue}▶ 正在验证sudo权限，请输入您的密码...${NC}"

if sudo -v; then
    echo -e "\n${green}【成功】sudo权限验证通过，继续执行后续操作${NC}"
else
    echo -e "\n${red}【错误】sudo权限验证失败！原因可能是：${NC}" 
    echo -e "${yellow}1. 当前用户未配置sudo权限"
    echo -e "2. 密码输入错误"
    exit 1
fi

# 用户确认函数：提示用户确认操作（y/n），返回 0（确认）或 1（取消）
confirm_operation() {
    echo -en "${yellow}$1 (y/n): ${reset}"
    read -r response
    [[ "$response" =~ ^[Yy]$ ]] && return 0 || return 1  
}

# ====================== 2）网络设置菜单开始 ======================
# 网络设置菜单：处理网络相关配置
network_menu() {
    while true; do
        clear
        echo -e "${blue}======================  银河麒麟工具箱  =====================${reset}"        
        echo -e "${green}╔══════════════════════════════════════════════════════════╗"
        echo -e "║                           网络设置                       ║"
        echo -e "╚══════════════════════════════════════════════════════════╝${reset}"            
        echo -e " ${magenta}1)${reset} 网络速度控制"
        echo -e " ${magenta}2)${reset} DNS解析优化"
        echo -e " ${magenta}3)${reset} Samba共享管理"
        echo -e " ${magenta}4)${reset} Samba获取列表失败"        
        echo -e " ${red}0)${reset} 返回主菜单"

        echo -e "${blue}$(printf '═%.0s' $(seq 1 60))${reset}"
        echo -en "${yellow}请输入选项编号 [ 例如：1 ]: ${reset}"
        read -rp "" choice
        case $choice in
            1) control_network_speed; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            2) optimize_dns_resolution; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            3) manage_samba_share; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            4) samba_share_list; echo -e "\n${yellow}按Enter键继续...${reset}"; read -r ;;
            0) echo -e "${green}→ 正在返回主菜单...${reset}";  break ;;
            *) echo -e "${red}✗ 无效选择，请重新输入！${reset}"; sleep 0.5;;
        esac
        echo -e "\n${yellow}按Enter键继续...${reset}"
        read -r
    done
}

# ====================== 网络设置子菜单 ======================
# 网络速度控制：支持限制网速、修改传输速率、清除限制
control_network_speed() {
    echo -e "${cyan}>>> 网络速度控制${reset}"
    # 获取可用网络接口
    interfaces=($(ip -o link show | awk -F': ''{print $2}'))
    echo -e "${yellow}可用网络接口:${reset}"
    for i in "${!interfaces[@]}"; do
        echo "$((i+1))) ${interfaces[$i]}"
    done
    # 选择网络接口
    read -rp "选择接口编号: " iface_num
    selected_iface=${interfaces[$((iface_num-1))]}
    # 选择操作类型
    echo -e "\n1) 限制网速\n2) 修改传输速率\n3) 清除限制"
    read -rp "选择操作: " op
    case $op in  
        1)  # 网速限制（依赖wondershaper工具）
            read -rp "下载速度(kbps): " down_speed
            read -rp "上传速度(kbps): " up_speed
            if ! command -v wondershaper &> /dev/null; then
                sudo apt install -y wondershaper
            fi
            sudo wondershaper $selected_iface $down_speed $up_speed
            ;;
        2)  # 传输速率修改（全双工/半双工）
            ethtool $selected_iface | grep "Advertised link modes"  
            read -rp "输入速率(如1000): " speed
            read -rp "双工模式(full/half): " duplex
            sudo ethtool -s $selected_iface autoneg off speed $speed duplex $duplex
            # 持久化配置
            sudo tee /etc/networkd-dispatcher/config.d/ethtool.conf <<EOF
if [ "\$IFACE" = "$selected_iface" ]; then
    /sbin/ethtool -s \$IFACE autoneg off speed $speed duplex $duplex
fi
EOF
            ;;
        3)  # 清除网速限制
            sudo wondershaper clean $selected_iface
            ;;
    esac
    echo -e "${green}[通知] 网络设置完成${reset}"
}

# DNS解析慢修复：添加国内公共DNS服务器
optimize_dns_resolution() {
    echo -e "${cyan}>>> 修复DNS解析慢${reset}"
    if ! grep -q "nameserver 223.5.5.5" /etc/resolv.conf; then
        echo "nameserver 223.5.5.5" | sudo tee -a /etc/resolv.conf
        echo "nameserver 119.29.29.29" | sudo tee -a /etc/resolv.conf
        echo "nameserver 114.114.114.114" | sudo tee -a /etc/resolv.conf        
        echo -e "${green}[通知] 已添加国内DNS服务器${reset}"
    else
        echo -e "${yellow}DNS配置已存在${reset}"
    fi
}

# Samba共享部署管理：安装配置/关闭服务/查看状态
manage_samba_share() {
    echo -e "${cyan}>>> Samba共享部署管理${reset}"
    echo -e "1) 安装并配置Samba共享"
    echo -e "2) 关闭Samba共享服务"
    echo -e "3) 查看当前共享状态"
    read -rp "请选择操作: " choice
    case $choice in
        1)  # 安装并配置Samba共享
            if ! command -v samba &> /dev/null; then
                sudo apt install -y samba
            fi
            read -rp "请输入要共享的目录路径: " share_dir
            read -rp "请输入共享名称: " share_name
            read -rp "请输入访问用户名: " samba_user
            # 创建共享目录并设置权限
            sudo mkdir -p "$share_dir"
            sudo chmod 777 "$share_dir"
            # 添加Samba配置
            sudo tee -a /etc/samba/smb.conf <<EOF
[$share_name]
   path = $share_dir
   browseable = yes
   writable = yes
   guest ok=yes 
   create mask = 0777
   directory mask= 0777
EOF
            # 设置Samba用户密码
            sudo smbpasswd -a "$samba_user"
            # 重启Samba服务
            sudo systemctl restart smbd nmbd
            echo -e "${green}[通知] Samba共享已启用${reset}"
            ;;
        2)  # 关闭Samba共享服务
            sudo systemctl stop smbd nmbd
            sudo systemctl disable smbd nmbd
            echo -e "${green}[通知] Samba共享服务已停止并禁用${reset}"
            ;;
        3)  # 查看当前共享状态
            smbstatus
            testparm -s
            ;;
        *)  # 无效选择
            echo -e "${red}无效选择${reset}"
            sleep 0.5
            ;;
    esac
}

#修复samb从服务器获取共享列表失败问题
samba_share_list() {
# 检查 samba 状态
systemctl status smbd
# 检查端口（假设检查 445 端口，可根据实际情况调整）
ss -tuln | grep 445
# 修改 smb.conf 配置文件，添加 server min protocol = LANMAN1 到 [global] 模块
sudo sed -i '/\[global\]/a server min protocol = LANMAN1' /etc/samba/smb.conf
# 重启 smbd 服务
sudo systemctl restart smbd
echo "Samba 配置已修改并重启服务，可尝试添加共享文件夹"
}
# 执行主函数 
network_menu

# 添加循环保护，防止意外退出
if [ $? -ne 0 ]; then
    echo -e "${red}菜单执行出错，3秒后返回主菜单...${reset}"
    sleep 3
fi